package com.wonders.framework.util.security;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.util.encoders.Base64;

import com.wonders.framework.exception.FrameworkException;

/**
 * AES加密算法工具
 * 
 * @author WuBin
 * 
 */
public class AesUtil {

	/**
	 * 转换密钥
	 * 
	 * @param key
	 *            密钥字符
	 * @return 密钥
	 */
	public static SecretKey parseSecretKey(String key) {
		try {
			return new SecretKeySpec(Base64.decode(key), "AES");
		} catch (Exception e) {
			throw new FrameworkException("转换私钥失败", e);
		}
	}

	/**
	 * 加密
	 * 
	 * @param secretKey
	 *            密钥
	 * @param data
	 *            待加密数据
	 * @return 加密数据
	 */
	public static byte[] encrypt(SecretKey secretKey, byte[] data) {
		try {
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			cipher.init(1, secretKey, new IvParameterSpec(new byte[] { 0, 0, 0,
					0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }));
			return cipher.doFinal(data);
		} catch (Exception e) {
			throw new FrameworkException("加密失败", e);
		}
	}

	/**
	 * 解密
	 * 
	 * @param secretKey
	 *            密钥
	 * @param data
	 *            待解密数据
	 * @return 数据
	 */
	public static byte[] decrypt(SecretKey secretKey, byte[] data) {
		try {
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			cipher.init(2, secretKey, new IvParameterSpec(new byte[] { 0, 0, 0,
					0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }));
			return cipher.doFinal(data);
		} catch (Exception e) {
			throw new FrameworkException("解密失败", e);
		}
	}

}
